<template>
  <a-drawer
    title="json代码"
    placement="right"
    :visible="visible"
    :keyboard="true"
    width="30vw"
    @close="
      () => {
        this.visible = false;
      }
    "
  >
    <div class="code_bg" ref="codeBg">
      <div class="icon_btn">
        <a-icon class="icon_style" @click="checkCodeType" type="swap" />
        <a-icon class="icon_style" type="copy" @click="copyCode" />
      </div>
      <div
        class="code_area"
        :style="{ height: codeHeight }"
        v-if="isCommont"
        oncontextmenu="return false"
        ondragstart="return false"
        onselectstart="return false"
        onselect="document.selection.empty()"
        oncopy="document.selection.empty()"
        onbeforecopy="return false"
      >
        {{ codeArr }}
      </div>
      <pre
        class="code_area"
        :style="{ height: codeHeight }"
        style="white-space: pre"
        v-else
        oncontextmenu="return false"
        ondragstart="return false"
        onselectstart="return false"
        onselect="document.selection.empty()"
        oncopy="document.selection.empty()"
        onbeforecopy="return false"
        >{{ codeArr }}</pre
      >
    </div>
  </a-drawer>
</template>

<script>
export default {
  data() {
    return {
      visible: false,
      isCommont: true,
      codeHeight: "0px",
    };
  },
  props: {
    codeArr: {
      type: Array || Object,
      default: "",
    },
  },
  methods: {
    showDrawe() {
      this.visible = true;
      this.$nextTick(() => {
        this.codeHeight = `${this.$refs.codeBg?.offsetHeight - 40 || 0}px`;
      });
    },
    checkCodeType() {
      this.isCommont = !this.isCommont;
    },
    copyCode() {
      let str = this.isCommont
        ? JSON.stringify(this.codeArr)
        : JSON.stringify(this.codeArr, null, 4);
      this.$copyText(str)
        .then(() => {
          this.$toast("复制成功");
        })
        .catch(() => {
          this.$toast.fail("该浏览器不支持复制");
        });
    },
  },
};
</script>

<style lang="less" scoped>
.code_bg {
  position: relative;
  display: flex;
  flex-direction: column;
  padding: 40px 20px 20px;
  box-sizing: border-box;
  height: 100%;
  border-radius: 6px;
  color: rgba(255, 255, 255, 0.8);
  background-color: rgb(15, 15, 15);

  .code_area {
    overflow-y: scroll;
  }

  .icon_btn {
    position: absolute;
    top: 20px;
    right: 20px;
    font-size: 20px;
    display: flex;
    justify-content: flex-end;

    .icon_style {
      margin-right: 14px;
      cursor: pointer;
      &:nth-last-child(1) {
        margin-right: 0;
      }
      &:hover {
        color: #fff;
      }
    }
  }
}
/deep/.ant-drawer-wrapper-body {
  display: flex;
  flex-direction: column;
}

/deep/ .ant-drawer-body {
  flex: 1;
}
</style>
